package com.customization.test.demo.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.customization.test.demo.service.WDetailsService;
import com.customization.unionpay.market.util.FormDataUtils;
import com.engine.core.impl.Service;
import com.engine.cube.biz.ShardingActionHelper;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.formmode.setup.ModeRightInfo;
import weaver.hrm.User;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class WDetailsServiceImpl  extends Service implements WDetailsService {

    private static final Logger log = LoggerFactory.getLogger(WDetailsServiceImpl.class);

    @Override
    public void addOrUpdateInfo(int formId, int formmodeId, User user, String csr, String xb, String js, String bm, String csrq ) throws Exception {

        try {
            // 获取主表表名
            String maintablename = FormDataUtils.getTableName(formId);

            List<JSONObject> lists = selectInfoBySth(maintablename, csr, xb, bm, csrq);
            if(lists.size() > 0){
                // 修改
                String id = lists.get(0).getString("id");
                updateInfoById(maintablename,id,js);
            }else {
                // 新增
                addInfoByFormId(formId,formmodeId,maintablename,user,csr,xb,js, bm, csrq);
            }
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    }

    @Override
    public void comfirmDataInfo(List<JSONObject> chooseFormData) {

    }

    @Override
    public String clearingTest(String ids, User user) throws Exception {
        String result = null;

        int formId = -299;
        int formmodeId = 264;
        String tableName = FormDataUtils.getTableName(formId);

        List<JSONObject> clearTestById = getClearTestById(tableName, ids);
        for (JSONObject jsonObject : clearTestById) {
            String id = jsonObject.getString("id");
            String js = jsonObject.getString("js");
            String xb = jsonObject.getString("xb");
            if(js == null || js.equals("")){
                throw new Exception("介绍为空");
            }else if("嘻嘻".equals(js)){
                String ywlxDetails = FormDataUtils.getItemName(formId, "xb", xb);
                if(result != null){
                    result += ","+"测试数据id:"+id+ywlxDetails;
                }else {
                    result = "";
                    result +="测试数据id:"+id+ywlxDetails;
                }
            }
        }
        return result;
    }

    private List<JSONObject> selectInfoBySth(String maintablename,String csr,String xb,String bm, String csrq ){
        RecordSet rst = new RecordSet();

        // 根据当前信息使用id修改新建数据
        String updateSql = "select id from " + maintablename + " where csr = '" + csr+"' and xb='" + xb+"' and bm='" + bm+"' and csrq='" + csrq+"' " ;
        rst.executeQuery(updateSql);

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()){
            JSONObject json = new JSONObject();
            json.put("id",rst.getString("id"));
            list.add(json);
        }
        return list;
    }


    private void addInfoByFormId(int formId,int formmodeId,String maintablename,User user,String csr, String xb, String js, String bm, String csrq ){
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        // 先调用内部方法新建一条数据，获取数据id
        int billid = FormDataUtils.getBillId(maintablename, formmodeId, user.getUID(), user.getType());

        try {
            // 获取formbizid
            String formBizId = ShardingActionHelper.constructBizId(billid, formId);

            // 根据当前信息使用id修改新建数据
            String updateSql = "update " + maintablename + " set csr='" + csr + "'," +
                    " xb='" + xb + "'," +
                    " js='" + js + "'," +
                    " bm='" + bm + "'," +
                    " csrq='" + csrq + "'," +
                    " form_biz_id = '" + formBizId + "' where id = " + billid;
            rst.executeUpdate(updateSql);
            // 提交事务
            rst.commit();

            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(1, formmodeId, billid);

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            deleteByBillId(maintablename, billid);
            log.error("添加数据异常："+e.getMessage());
        }
    }

    private void updateInfoById(String maintablename,String id ,String js ){
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);
        try {

            // 根据当前信息使用id修改新建数据
            String updateSql = "update " + maintablename + " set  js='" + js + "' where id = " + id;
            rst.executeUpdate(updateSql);
            // 提交事务
            rst.commit();

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("修改数据异常："+e.getMessage());
        }
    }

    private void deleteByBillId(String maintablename,int billid){
        RecordSetTrans rst = new RecordSetTrans();
        // 开启事务（关闭自动提交）
        rst.setAutoCommit(false);

        try {
            // 根据当前信息使用id修改新建数据
            String updateSql = "delete from " + maintablename + "  where id = " + billid;
            rst.executeUpdate(updateSql);
            // 提交事务
            rst.commit();

        } catch (Exception e) {
            // 回滚
            rst.rollback();
            log.error("删除数据异常："+e.getMessage());
        }
    }


    public static List<JSONObject> getClearTestById(String maintablename, String ids) {
        RecordSet rst = new RecordSet();
        // 根据当前信息使用id修改新建数据
//        String sql = "select id,js,xb from " + maintablename + " where id in (" + ids + ") ";
        String sql = "select id,js,xb from #{tableName} where id in (?) ";
//        rs.executeQuery("SELECT id FROM LgcAsset WHERE assortmentid=?",supAssortmentId);

        sql = sql.replace("#{tableName}", maintablename);
        rst.executeQuery(sql,ids);

        List<JSONObject> list = new ArrayList<>();
        while (rst.next()) {
            JSONObject json = new JSONObject();
            json.put("id", rst.getString("id"));
            json.put("js", rst.getString("js"));
            json.put("xb", rst.getString("xb"));
            list.add(json);
        }
        return list;
    }
}
